//
// Created by TNJ on 2021/6/10.
//
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"

void queue_arr_init(queue_arr_t *q, int capacity){
    if(q == NULL || capacity <= 0){
        return;
    }
    q->head = 0;
    q->tail = 0;
    q->size = 0;
    q->arr = malloc(capacity * sizeof(int));
    q->cap = capacity;
}

void enqueue_arr(queue_arr_t *q, int data){
    if(q == NULL){
        return;
    }
    if(queue_arr_is_full(q)){
        return;
    }
    //循环重用使用过的内存
    if(q->tail >= q->cap){
        q->tail = 0;
    }
    q->arr[q->tail++] = data;
    q->size++;
}

int dequeue_arr(queue_arr_t *q){
    if(q == NULL){
        return NAN;
    }
    if(queue_arr_is_empty(q)){
        return NAN;
    }
    if(q->head >= q->cap){
        q->head = 0;
    }
    q->size--;
    return q->arr[q->head++];
}

void queue_arr_destroy(queue_arr_t *q){
    if(q == NULL){
        return;
    }
    if(q->arr){
        free(q->arr);
    }
    q->arr = NULL;
    q->tail = 0;
    q->head = 0;
    q->cap = 0;
    q->size = 0;
}

bool queue_arr_is_full(queue_arr_t *q){
    if(q == NULL){
        return false;
    }
    return q->size == q->cap ? true : false;
}

bool queue_arr_is_empty(queue_arr_t *q){
    if(q == NULL){
        return true;
    }
    return q->size == 0 ? true : false;
}

int queue_arr_length(queue_arr_t *q){
    if(q == NULL){
        return 0;
    }
    return q->size;
}
